<template>
  <div class="chat-window" v-if="visible">
    <div class="chat-header">
      <div class="chat-title">{{ $t('chat.chatWith') }} {{ targetUser }}</div>
      <div class="chat-close" @click="closeChat">×</div>
    </div>
    <div class="chat-body" ref="chatBody">
      <div v-if="messages.length === 0" class="no-message">{{ $t('chat.noMessages') }}</div>
      <div v-for="(msg, index) in messages" :key="index" class="message-item" :class="{'self': isCurrentUser(msg)}">
        <div class="message-avatar">
          <img :src="getAvatar(getUsernameFromMsg(msg))" alt="avatar">
        </div>
        <div class="message-content">
          <div class="message-name">{{ getUsernameFromMsg(msg) }}</div>
          <div class="message-text">{{ getContentFromMsg(msg) }}</div>
          <div class="message-time">{{ formatTime(msg.createdAt) }}</div>
        </div>
      </div>
    </div>
    <div class="chat-footer">
      <el-input
        v-model="messageText"
        :placeholder="$t('chat.typeSomething')"
        @keyup.enter.native="sendMessage"
        type="textarea"
        :rows="2"
      ></el-input>
      <el-button type="primary" @click="sendMessage">{{ $t('chat.send') }}</el-button>
    </div>
  </div>
</template>

<script>
import {sendMsg, getChatMessages} from '@/api/msg'
import socket from '@/utils/socket'

export default {
  name: 'ChatWindow',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    targetUser: {
      type: String,
      default: ''
    },
    targetEmail: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      messages: [],
      messageText: '',
      currentUser: localStorage.getItem('username') || '',
      currentEmail: localStorage.getItem('email') || '',
      socketConnected: false,
      pollingInterval: null,
      usePolling: false
    }
  },
  watch: {
    visible(val) {
      if (val && this.targetUser) {
        this.loadMessages()
        this.connectSocket()
      }
    },
    messages() {
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    }
  },
  methods: {
    startPolling() {
      if (this.pollingInterval) return

      this.usePolling = true
      console.log('启用轮询模式获取消息')

      this.pollingInterval = setInterval(() => {
        if (this.visible && this.targetUser) {
          this.loadMessages()
        }
      }, 3000) // 每5秒轮询一次
    },
    stopPolling() {
      if (this.pollingInterval) {
        clearInterval(this.pollingInterval)
        this.pollingInterval = null
      }
    },
    connectSocket() {
      // 检查 socket 是否已连接
      if (socket.connected) {
        this.socketConnected = true
        console.log('Socket 已连接')
        socket.emit('join', {username: this.currentUser})
        return
      }

      // 如果未连接，尝试连接
      console.log('尝试连接 Socket...')

      // 添加连接超时处理
      const connectionTimeout = setTimeout(() => {
        console.warn('Socket 连接超时，启用轮询模式')
        this.startPolling()
      }, 5000)

      socket.connect()

      // 监听连接事件
      socket.on('connect', () => {
        console.log('Socket 连接成功')
        this.socketConnected = true
        socket.emit('join', {username: this.currentUser})
        clearTimeout(connectionTimeout)
      })

      // 监听连接错误
      socket.on('connect_error', (error) => {
        console.error('Socket 连接错误:', error)
        this.socketConnected = false
      })
    },

    // 添加新的辅助方法来处理不同格式的消息
    isCurrentUser(msg) {
      return this.getUsernameFromMsg(msg) === this.currentUser;
    },

    getUsernameFromMsg(msg) {
      // 处理不同格式的消息对象
      if (msg.username) return msg.username;
      if (msg.sender) return msg.sender;
      if (msg.from_username) return msg.from_username;
      return '未知用户';
    },

    getContentFromMsg(msg) {
      // 处理不同格式的消息内容
      if (msg.content) return msg.content;
      if (msg.message) return msg.message;
      if (msg.messageText) return msg.messageText;
      return '无内容';
    },

    loadMessages() {
      // 查询与目标用户的聊天记录
      // const query = {
      //   query: { username: this.currentUser, receive: this.targetUser }
      // }
      const query = {
        username: this.currentUser, receive: this.targetUser,
        limit: 1000
      }

      getChatMessages(query).then(res => {
        console.log("res", res);
        if (res.meta.status === 200 && res.data) {
          console.log('获取到聊天记录:', res.data);

          // 检查消息格式并打印第一条消息的结构
          if (res.data && res.data.length > 0) {
            console.log('第一条消息结构:', JSON.stringify(res.data[0]));
          }

          // 确保消息数组是有效的
          const messageArray = res.data || [];

          // 清空现有消息并添加新消息
          this.messages = [];

          // 添加消息到列表 - 反转数组，使最新的消息在底部
          messageArray.forEach(msg => {
            this.messages.push(msg);
          });

          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          console.error('获取聊天记录失败:', res);
        }
      }).catch(err => {
        console.error('获取聊天记录异常:', err);
      });
    },

    sendMessage() {
      if (!this.messageText.trim()) return;

      const msgData = {
        username: this.currentUser,
        email: this.currentEmail,
        receive: this.targetUser,
        content: this.messageText,
        // createdAt: new Date().toISOString() // 确保有时间戳
      };

      // 发送消息到服务器
      sendMsg(msgData).then(res => {
        if (res.meta.status === 200) {
          console.log('消息发送成功');

          // 添加到本地消息列表
          this.messages.push(msgData);

          // 通过WebSocket发送实时消息
          if (this.socketConnected) {
            socket.emit('chat message', msgData);
            console.log('WebSocket 消息已发送');
          } else {
            console.warn('WebSocket 未连接，无法发送实时消息');
          }

          // 清空输入框
          this.messageText = '';

          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          console.error('消息发送失败:', res);
          this.$message.error('消息发送失败');
        }
      }).catch(err => {
        console.error('消息发送异常:', err);
        this.$message.error('消息发送异常');
      });
    },
    closeChat() {
      this.$emit('update:visible', false)
    },
    scrollToBottom() {
      if (this.$refs.chatBody) {
        this.$refs.chatBody.scrollTop = this.$refs.chatBody.scrollHeight
      }
    },
    getAvatar(username) {
      // 简单的头像生成逻辑，实际项目中可以替换为用户真实头像
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random`
    },
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }
  },
  mounted() {
    // 连接 Socket
    this.connectSocket()

    // 立即加载消息
    if (this.visible && this.targetUser) {
      this.loadMessages();
    }

    // 监听新消息
    socket.on('chat message', (msg) => {
      console.log('收到新消息:', msg);

      // 只处理与当前聊天相关的消息
      const msgUsername = this.getUsernameFromMsg(msg);
      const msgReceiver = msg.receive || msg.receiver || '';

      if ((msgUsername === this.targetUser && msgReceiver === this.currentUser) ||
        (msgUsername === this.currentUser && msgReceiver === this.targetUser)) {
        console.log('添加消息到列表');
        this.messages.push(msg);

        // 滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    });
  },
  beforeDestroy() {
    // 移除所有事件监听
    socket.off('chat message')
    socket.off('connect')
    socket.off('connect_error')
    this.stopPolling()
  }
}
</script>

<style scoped lang="less">
.chat-window {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 350px;
  height: 450px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  z-index: 1000;
  transition: all 0.3s ease;
  overflow: hidden;

  &:hover {
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
  }

  .chat-header {
    padding: 12px 15px;
    background: linear-gradient(135deg, #ff6d6d, #ff4f81);
    color: white;
    border-radius: 12px 12px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .chat-title {
      font-weight: bold;
      font-size: 16px;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }

    .chat-close {
      cursor: pointer;
      font-size: 24px;
      line-height: 20px;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      transition: all 0.2s ease;

      &:hover {
        background-color: rgba(255, 255, 255, 0.2);
        transform: scale(1.1);
      }
    }
  }

  .chat-body {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    background: #f9f9f9;
    background-image: linear-gradient(rgba(255, 255, 255, 0.7) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.7) 1px, transparent 1px);
    background-size: 20px 20px;
    background-position: center center;
    scroll-behavior: smooth;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.1);
      border-radius: 3px;

      &:hover {
        background: rgba(0, 0, 0, 0.15);
      }
    }

    .no-message {
      text-align: center;
      color: #999;
      margin-top: 30%;
      font-style: italic;
      opacity: 0.7;
    }

    .message-item {
      display: flex;
      margin-bottom: 18px;
      animation: fadeIn 0.3s ease;

      &.self {
        flex-direction: row-reverse;

        .message-content {
          background: linear-gradient(135deg, #ff6d6d, #ff4f81);
          color: white;
          border-radius: 15px 0 15px 15px;
          margin-left: 0;
          margin-right: 10px;
          box-shadow: 0 2px 5px rgba(255, 109, 109, 0.2);

          .message-name {
            text-align: right;
            color: rgba(255, 255, 255, 0.8);
          }

          .message-time {
            text-align: right;
            color: rgba(255, 255, 255, 0.7);
          }
        }
      }

      .message-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s ease;

        &:hover {
          transform: scale(1.05);
        }

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
        }
      }

      .message-content {
        max-width: 70%;
        background: white;
        padding: 12px 15px;
        border-radius: 0 15px 15px 15px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        margin-left: 10px;
        transition: transform 0.2s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        .message-name {
          font-size: 12px;
          color: #888;
          margin-bottom: 5px;
          font-weight: 500;
        }

        .message-text {
          word-break: break-word;
          line-height: 1.4;
          font-size: 14px;
        }

        .message-time {
          font-size: 11px;
          color: #aaa;
          margin-top: 6px;
          text-align: right;
        }
      }
    }
  }

  .chat-footer {
    padding: 12px;
    border-top: 1px solid #eee;
    display: flex;
    align-items: flex-end;
    background: white;

    .el-input {
      margin-right: 10px;
      flex: 1;

      /deep/ .el-textarea__inner {
        border-radius: 18px;
        padding: 8px 15px;
        resize: none;
        transition: all 0.3s ease;
        border: 1px solid #e0e0e0;

        &:focus {
          border-color: #ff6d6d;
          box-shadow: 0 0 0 2px rgba(255, 109, 109, 0.2);
        }
      }
    }

    .el-button {
      height: 40px;
      border-radius: 20px;
      padding: 0 20px;
      background: linear-gradient(135deg, #ff6d6d, #ff4f81);
      border: none;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(255, 109, 109, 0.3);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
